/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2016-10-11 16:00:43
 * Last Modified: 2017-08-01 16:53:11
 * File Name: rpc/client/location.go
 * Description:
 */
package openapi

import (
	"crypto/tls"
	"fmt"

	"github.com/astaxie/beego/httplib"
	log "github.com/cihub/seelog"
)

func GeoLocation(lng, lat string) map[string]interface{} {
	reqURL := fmt.Sprintf("https://%s/v1/geohash/location?appkey=140a6d51d67c477e83cd91a241678824&lat=%s&lng=%s", openapiHost, lat, lng)
	b := httplib.Get(reqURL)
	b.SetHost(openapiHost)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	resp := make(map[string]interface{})
	if err := b.ToJSON(&resp); err != nil {
		log.Warnf("GeoLocation error: %s, reqURL: %s", err.Error(), reqURL)
		return map[string]interface{}{"addr_format": ""}
	}
	if data, ok := resp["data"]; ok && data != nil {
		dt := data.(map[string]interface{})
		return map[string]interface{}{"addr_format": dt["addr_format"].(string)}
	}
	return map[string]interface{}{"addr_format": ""}
}

func ParseRegionCode(regionCode string) map[string]interface{} {
	reqURL := fmt.Sprintf("https://%s/v1/cr/parse-region?appkey=140a6d51d67c477e83cd91a241678824&regionid=%s", openapiHost, regionCode)
	b := httplib.Get(reqURL)
	b.SetHost(openapiHost)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	resp := make(map[string]interface{})
	if err := b.ToJSON(&resp); err != nil {
		log.Warnf("parse-region error: %s, reqURL: %s", err.Error(), reqURL)
		return map[string]interface{}{"admin_addr": ""}
	}
	if dt, ok := resp["data"]; ok && dt != nil {
		data := dt.(map[string]interface{})
		addr := data["city"].(string) + data["county"].(string) + data["town"].(string)
		return map[string]interface{}{"admin_addr": addr}
	}
	return map[string]interface{}{"admin_addr": ""}
}
